package com.beg.cant.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.beg.cant.comment.DeletionNotAllowedException;
import com.beg.cant.comment.MessageConstant;
import com.beg.cant.comment.properties.WeChatProperties;
import com.beg.cant.comment.utils.HttpClientUtil;
import com.beg.cant.comment.utils.UniqueIdGenerator;
import com.beg.cant.dto.PageRequest;
import com.beg.cant.dto.PageResponse;
import com.beg.cant.entity.Order;
import com.beg.cant.entity.Post;
import com.beg.cant.entity.User;
import com.beg.cant.mapper.OrderMapper;
import com.beg.cant.mapper.PostMapper;
import com.beg.cant.mapper.UserMapper;
import com.beg.cant.service.UserService;
import com.beg.cant.vo.UserVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    public static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";
    private final UserMapper userMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private PostMapper postMapper;

    public User wxLogin(String code){
        // 获取微信 openid
        String openid = getOpenid(code);
        if (openid == null || openid.isEmpty()) {
            throw new DeletionNotAllowedException(MessageConstant.LOGIN_FAILED);
        }

        // 使用 selectList 查询所有匹配记录
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getOpenid, openid);
        List<User> users = userMapper.selectList(queryWrapper); // 

        if (users.isEmpty()) {
            // 是新用户，插入数据并回显 id
            User newUser = User.builder()
                    .id(UniqueIdGenerator.generateUniqueId())
                    .openid(openid)
                    .name("用户"+ UniqueIdGenerator.generateUniqueId())
                    .createdAt(LocalDateTime.now())
                    .total(1.00)
                    .image("/static/default-avatar.png")
                    .image("https://ts1.cn.mm.bing.net/th?id=OIP-C.RFgnRHK1YvW7-fUS-v8L1AAAAA&w=160&h=211&c=8&rs=1&qlt=90&o=6&dpr=1.1&pid=3.1&rm=2")
                    .build();
            // 插入新用户并获取生成的 ID
            userMapper.insert(newUser);
            return newUser;
        } else {
            // 返回现有用户信息
            return users.get(0);
        }
    }

    @Override
    public UserVO getUserById(Long id) {
        // 获取日期范围
        LocalDate today = LocalDate.now();
        LocalDate yesterday = today.minusDays(1);

        LocalDateTime startOfToday = today.atStartOfDay();
        LocalDateTime endOfToday = LocalDateTime.of(today, LocalTime.MAX); // 

        LocalDateTime startOfYesterday = yesterday.atStartOfDay();
        LocalDateTime endOfYesterday = LocalDateTime.of(yesterday, LocalTime.MAX);

        LambdaQueryWrapper<Order> todayWrapper = new LambdaQueryWrapper<Order>()
                .between(Order::getCreatedAt, startOfToday, endOfToday)
                .eq(Order::getStatus, 1);

        LambdaQueryWrapper<Order> yesterdayWrapper = new LambdaQueryWrapper<Order>()
                .between(Order::getCreatedAt, startOfYesterday, endOfYesterday)
                .eq(Order::getStatus, 1);
        User user = userMapper.selectById(id);
        LambdaQueryWrapper<Post> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Post::getUserId,id);
        // 构建 VO
        return UserVO.builder()
                .follows(getSum(todayWrapper))
                .fans(getSum(yesterdayWrapper))
                .createdAt(user.getCreatedAt())
                .total(user.getTotal())
                .image(user.getImage())
                .count(postMapper.selectCount(wrapper))
                .name(user.getName())
                .id(user.getId())
                .build();
    }
    private Double getSum(LambdaQueryWrapper<Order> wrapper) {
        // 查询符合条件的订单列表
        List<Order> orders = orderMapper.selectList(wrapper);
        // 遍历列表累加 fee 值
        return orders.stream()
                .filter(order -> order.getFee() != null) // 过滤空值
                .mapToDouble(Order::getFee)
                .sum();
    }
    /**
     * 
     * @param code
     * @return
     */
    private String getOpenid(String code){
        //,openid
        Map<String, String> map = new HashMap<>();
        map.put("appid",weChatProperties.getAppid());
        map.put("secret",weChatProperties.getSecret());
        map.put("js_code",code);
        map.put("grant_type","authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN, map);

        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        System.out.println(map);
        System.out.println(jsonObject);
        System.out.println(openid);
        return openid;
    }

    @Override
    public PageResponse<UserVO> getUserList(PageRequest pageRequest) {
        Page<User> page = new Page<>(pageRequest.getPageNum(), pageRequest.getPageSize());
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        
        // 添加时间范围筛选
        if (pageRequest.getStartTime() != null) {
            wrapper.ge(User::getCreatedAt, pageRequest.getStartTime());
        }
        if (pageRequest.getEndTime() != null) {
            wrapper.le(User::getCreatedAt, pageRequest.getEndTime());
        }
        // 添加code筛选
        if (pageRequest.getCode()!=null){
            wrapper.eq(User::getId,pageRequest.getCode());
        }
        wrapper.orderByAsc(User::getTotal).orderByDesc(User::getCreatedAt);
        IPage<User> userPage = userMapper.selectPage(page, wrapper);
        return PageResponse.of(userPage.getRecords().stream().map(item->{
            LambdaQueryWrapper<Post> postWrapper = new LambdaQueryWrapper<>();
            postWrapper.eq(Post::getUserId,item.getId());
            UserVO build = UserVO.builder()
                    .count(postMapper.selectCount(postWrapper))
                    .build();
            BeanUtils.copyProperties(item,build);
            return build;
        }).toList(), userPage.getTotal(), pageRequest);
    }

    @Override
    public List<UserVO> getTopBalanceUsers() {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(User::getTotal)
               .last("LIMIT 5");
        
        return userMapper.selectList(wrapper).stream()
                .map(user -> {
                    LambdaQueryWrapper<Post> postWrapper = new LambdaQueryWrapper<>();
                    postWrapper.eq(Post::getUserId, user.getId());
                    UserVO userVO = UserVO.builder()
                            .count(postMapper.selectCount(postWrapper))
                            .build();
                    BeanUtils.copyProperties(user, userVO);
                    return userVO;
                })
                .toList();
    }
}
